package com.theme.passport.controller.app;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.theme.common.base.DateHandler;
import com.theme.common.mvc.utils.PageUtils;
import com.theme.common.mvc.utils.Query;
import com.theme.common.mvc.view.R;
import com.theme.passport.entity.SysUserEntity;
import com.theme.passport.entity.constant.DownloadTypeEnum;
import com.theme.passport.entity.constant.ThemeAttchmentTypeEnum;
import com.theme.passport.entity.constant.ThemeStatusEnum;
import com.theme.passport.entity.constant.WidgeSizeEnum;
import com.theme.passport.entity.params.WidgePreviews;
import com.theme.passport.entity.theme.ThemeAttachmentEntity;
import com.theme.passport.entity.theme.WidgeConfigEntity;
import com.theme.passport.entity.theme.WidgeEntity;
import com.theme.passport.entity.theme.WidgeWeatherImagesEntity;
import com.theme.passport.service.SysUserService;
import com.theme.passport.service.theme.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author: 可乐加糖
 * @create: 2022-06-28 16:30
 * @Description: 组件管理
 */
@RestController
@RequestMapping("app/widges")
@Api("组件管理相关接口")
public class WidgesController {

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private WidgeService widgeService;

    @Autowired
    private WidgeClassifyService widgeClassifyService;

    @Autowired
    private WidgeTypeService widgeTypeService;

    @Autowired
    private WidgeConfigService widgeConfigService;

    @Autowired
    private DownloadHistoryService downloadHistoryService;

    @Autowired
    private ThemeAttachmentService attachmentService;

    @Autowired
    private WidgeWeatherImagesService widgeWeatherImagesService;


    @GetMapping("classify")
    @ApiOperation("获取组件分类接口")
    public R classify(@RequestParam(value = "keyword", required = false) String keyword,
                      @RequestParam(value = "page", defaultValue = "1") String page,
                      @RequestParam(value = "limit", defaultValue = "10") String limit) {
        Map<String, Object> params = new HashMap<>();
        params.put("key", keyword);
        params.put("page", page);
        params.put("limit", limit);
        PageUtils pages = widgeClassifyService.queryPage(params);
        return R.ok().put("page", pages);
    }

    @GetMapping("type")
    @ApiOperation("获取组件类型接口")
    public R type(@RequestParam(value = "keyword", required = false) String keyword,
                  @RequestParam(value = "page", defaultValue = "1") String page,
                  @RequestParam(value = "limit", defaultValue = "10") String limit) {
        Map<String, Object> params = new HashMap<>();
        params.put("key", keyword);
        params.put("page", page);
        params.put("limit", limit);
        PageUtils pages = widgeTypeService.queryPage(params);
        return R.ok().put("page", pages);
    }

    @GetMapping("list")
    @ApiOperation("获取组件列表")
    public R list(@RequestParam(value = "keyword", required = false) String keyword,
                  @RequestParam(value = "typeId", required = false) String typeId,
                  @RequestParam(value = "free", required = false) String free,
                  @RequestParam(value = "classifyId", required = false) String classifyId,
                  @RequestParam(value = "page", defaultValue = "1") String page,
                  @RequestParam(value = "limit", defaultValue = "10") String limit) {
        Integer status = ThemeStatusEnum.NORMAL.getValue();
        Map<String, Object> params = new HashMap<>();
        params.put("status", String.valueOf(status));
        params.put("free", free);
        params.put("key", keyword);
        params.put("typeId", typeId);
        params.put("classifyId", classifyId);
        params.put("page", page);
        params.put("limit", limit);
        params.put("themeShow", false);
        PageUtils pages = widgeService.queryPage(params);
        List<WidgeEntity> list = (List<WidgeEntity>) pages.getList();
        list.forEach(widge -> {
            //SysUserEntity byId = sysUserService.getById(widge.getUserId());
            //widge.setUseNickname(byId.getNickname());
        });
        pages.setList(list);
        return R.ok().put("page", pages);
    }

    @GetMapping("groupNameList")
    @ApiOperation("获取组件列表基于name分组")
    public R groupNameList(@RequestParam(value = "free", required = false) String free,
                           @RequestParam(value = "keyword", required = false) String keyword,
                           @RequestParam(value = "typeId", required = false) String typeId,
                           @RequestParam(value = "themeId", required = false) String themeId,
                           @RequestParam(value = "classifyId", required = false) String classifyId,
                           @RequestParam(value = "page", defaultValue = "1") String page,
                           @RequestParam(value = "limit", defaultValue = "10") String limit) {
        Integer status = ThemeStatusEnum.NORMAL.getValue();
        Map<String, Object> params = new HashMap<>();
        params.put("status", String.valueOf(status));
        params.put("key", keyword);
        params.put("free", free);
        params.put("typeId", typeId);
        params.put("themeId", themeId);
        params.put("classifyId", classifyId);
        params.put("page", page);
        params.put("limit", limit);
        params.put("themeShow", false);
        PageUtils pages = widgeService.queryPageBydistinctName2(params);
        List<WidgeEntity> list = (List<WidgeEntity>) pages.getList();
        list.forEach(theme -> {
            //同名组件列表
            List<WidgeEntity> widgeSizeList = widgeService.queryWidgeListByName(theme.getName());
            WidgeEntity widge = widgeSizeList.get(0);
            //SysUserEntity byId = sysUserService.getById(widge.getUserId());
            //widge.setUseNickname(byId.getNickname());
            BeanUtils.copyProperties(widge, theme);
            // 同名组件大小
            WidgePreviews widgePreviews = new WidgePreviews();
            widgeSizeList.forEach(item -> {
                String widgetSize = item.getWidgetSize();
                if (widgetSize.equals(WidgeSizeEnum.SMALL.getValue())) {
                    widgePreviews.setSmall(item.getPreview());
                }
                if (widgetSize.equals(WidgeSizeEnum.MEDIUM.getValue())) {
                    widgePreviews.setMidium(item.getPreview());
                }
                if (widgetSize.equals(WidgeSizeEnum.LAREGE.getValue())) {
                    widgePreviews.setLarge(item.getPreview());
                }
            });
            theme.setWidgePreviews(widgePreviews);
            theme.setWidgeSizeList(widgeSizeList);
        });
        pages.setList(list);

        return R.ok().put("page", pages);
    }

    @GetMapping("groupNameList/v2")
    @ApiOperation("获取组件列表基于name分组v2")
    public R groupNameListV2(@RequestParam(value = "free", required = false) String free,
                             @RequestParam(value = "keyword", required = false) String keyword,
                             @RequestParam(value = "typeId", required = false) String typeId,
                             @RequestParam(value = "themeId", required = false) String themeId,
                             @RequestParam(value = "classifyId", required = false) String classifyId,
                             @RequestParam(value = "page", defaultValue = "1") String page,
                             @RequestParam(value = "limit", defaultValue = "10") String limit) {
        Integer status = ThemeStatusEnum.NORMAL.getValue();
        Map<String, Object> params = new HashMap<>();
        params.put("status", String.valueOf(status));
        params.put("key", keyword);
        params.put("free", free);
        params.put("typeId", typeId);
        params.put("themeId", themeId);
        params.put("classifyId", classifyId);
        params.put("page", page);
        params.put("limit", limit);
        params.put("themeShow", false);
        PageUtils pages = widgeService.queryPageBydistinctNameV2(params);
        List<WidgeEntity> list = (List<WidgeEntity>) pages.getList();
        List<WidgeEntity> chilendList = new ArrayList<>();
        for (WidgeEntity theme : list) {
            List<WidgeEntity> widgeSizeList = widgeService.queryWidgeListByNameV2(theme.getName());
            chilendList.addAll(widgeSizeList);
        }
        for (WidgeEntity theme : list) {
            // 同名组件大小
            WidgePreviews widgePreviews = new WidgePreviews();
            for (WidgeEntity citem : chilendList) {
                if (theme.getName().equals(citem.getName())) {
                    String widgetSize = citem.getWidgetSize();
                    if (widgetSize.equals(WidgeSizeEnum.SMALL.getValue())) {
                        widgePreviews.setSmall(citem.getPreview());
                    }
                    if (widgetSize.equals(WidgeSizeEnum.MEDIUM.getValue())) {
                        widgePreviews.setMidium(citem.getPreview());
                    }
                    if (widgetSize.equals(WidgeSizeEnum.LAREGE.getValue())) {
                        widgePreviews.setLarge(citem.getPreview());
                    }
                    BeanUtils.copyProperties(citem, theme);
                }
            }
            theme.setWidgePreviews(widgePreviews);
        }
        List<WidgeEntity> returnList = new ArrayList<>();
        for (WidgeEntity item : list) {
            for (WidgeEntity citem : chilendList) {
                if (item.getName().equals(citem.getName())) {
                    WidgeEntity entity = new WidgeEntity();
                    BeanUtils.copyProperties(item, entity);
                    List<WidgeEntity> tempList = new ArrayList<>();
                    tempList.add(citem);
                    entity.setWidgeSizeList(tempList);
                    entity.setWidgetSize(tempList.get(0).getWidgetSize());
                    returnList.add(entity);
                }
            }
        }

        pages.setList(returnList);
        return R.ok().put("page", pages);
    }

    @GetMapping("featured")
    @ApiOperation("查询精选|福利组件接口[free表示1收费0免费]")
    public R featured(@RequestParam(value = "free", defaultValue = "1") String free,
                      @RequestParam(value = "keyword", required = false) String keyword,
                      @RequestParam(value = "classifyId", required = false) String classifyId,
                      @RequestParam(value = "typeId", required = false) String typeId,
                      @RequestParam(value = "themeId", required = false) String themeId,
                      @RequestParam(value = "page", defaultValue = "1") String page,
                      @RequestParam(value = "limit", defaultValue = "10") String limit) {
        return this.groupNameList(free, keyword, typeId, themeId, classifyId, page, limit);
    }

    @GetMapping("/info")
    @ApiOperation("查询组件详情")
    public R info(@RequestParam("widgeId") Long widgeId) {
        WidgeEntity widge = widgeService.getById(widgeId);
        if (widge == null) {
            return R.error("该组件不存在或已下架!!!");
        }
        SysUserEntity byId = sysUserService.getById(widge.getUserId());
        widge.setUseNickname(byId.getNickname());
        //同名组件列表
        List<WidgeEntity> widgeSizeList = widgeService.queryWidgeListByName(widge.getName());
        //同名组件大小
        WidgePreviews widgePreviews = new WidgePreviews();
        widgeSizeList.forEach(item -> {
            //组件预览图
            String widgetSize = item.getWidgetSize();
            if (widgetSize.equals(WidgeSizeEnum.SMALL.getValue())) {
                widgePreviews.setSmall(item.getPreview());
            }
            if (widgetSize.equals(WidgeSizeEnum.MEDIUM.getValue())) {
                widgePreviews.setMidium(item.getPreview());
            }
            if (widgetSize.equals(WidgeSizeEnum.LAREGE.getValue())) {
                widgePreviews.setLarge(item.getPreview());
            }
            //根据组件配置
            List<WidgeConfigEntity> widgeConfigList = widgeConfigService.queryWidgeConfigList(item.getId());
            widgeConfigList.forEach(itemConfig -> {
                //修改旧数据的文字类型
                if (itemConfig.getElement() == 1){
                    switch (itemConfig.getTextType()){
                        case 5:
                            //步数
                            itemConfig.setElement(8);
                            break;
                        case 6:
                            //温度
                            itemConfig.setElement(4);
                            break;
                        case 8:
                            //电量
                            itemConfig.setElement(3);
                            break;
                    }
                }
            });


            item.setWidgeConfigList(widgeConfigList);
        });
        widge.setWidgePreviews(widgePreviews);
        widge.setWidgeSizeList(widgeSizeList);

        //根据组件获取组件的配置列表
        List<WidgeConfigEntity> widgeConfig = widgeConfigService.queryWidgeConfigList(widgeId);
        widge.setWidgeConfigList(widgeConfig);

            //查询详情主题详情图附件
            QueryWrapper<ThemeAttachmentEntity> fileNameWrapper = new QueryWrapper<>();
            fileNameWrapper.and(wrapper -> wrapper
                    .eq("type", ThemeAttchmentTypeEnum.WIDGE.getValue())
                    .eq("object_id", widge.getId()));
            List<ThemeAttachmentEntity> attachmentList = attachmentService.list(fileNameWrapper);
            if (attachmentList != null && attachmentList.size() > 0) {
                List<String> imageList = new ArrayList<>();
                attachmentList.forEach(attachment -> {
                    imageList.add(attachment.getFileUrl());
                });
                widge.setWeatherImages(imageList);
            }

        return R.ok().put("widge", widge);
    }

    @GetMapping("/infoV3")
    @ApiOperation("查询组件详情")
    public R infov3(@RequestParam("widgeId") Long widgeId) {
        WidgeEntity widge = widgeService.getById(widgeId);
        if (widge == null) {
            return R.error("该组件不存在或已下架!!!");
        }
        SysUserEntity byId = sysUserService.getById(widge.getUserId());
        widge.setUseNickname(byId.getNickname());
        //同名组件列表
        List<WidgeEntity> widgeSizeList = widgeService.queryWidgeListByName(widge.getName());
        //同名组件大小
        WidgePreviews widgePreviews = new WidgePreviews();
        widgeSizeList.forEach(item -> {
            //组件预览图
            String widgetSize = item.getWidgetSize();
            if (widgetSize.equals(WidgeSizeEnum.SMALL.getValue())) {
                widgePreviews.setSmall(item.getPreview());
            }
            if (widgetSize.equals(WidgeSizeEnum.MEDIUM.getValue())) {
                widgePreviews.setMidium(item.getPreview());
            }
            if (widgetSize.equals(WidgeSizeEnum.LAREGE.getValue())) {
                widgePreviews.setLarge(item.getPreview());
            }
            //根据组件配置
            List<WidgeConfigEntity> widgeConfigList = widgeConfigService.queryWidgeConfigList(item.getId());
            widgeConfigList.forEach(itemConfig -> {
                //修改旧数据的文字类型
                switch (itemConfig.getElement()){
                    case 3:
                        //电量
                        itemConfig.setElement(1);
                        itemConfig.setTextType(8);
                        break;
                    case 4:
                        //温度
                        itemConfig.setElement(1);
                        itemConfig.setTextType(6);
                        if (null==itemConfig.getExtraInfo()&&itemConfig.getExtraInfo().equals("")){
                            itemConfig.setExtraInfo("{\"day\":\"0\",\"type\":\"average\"}");
                        }
                        break;
                    case 8:
                        //步数
                        itemConfig.setElement(1);
                        itemConfig.setTextType(5);
                        break;
                    case 1:
                        //文字
                        if (null!=itemConfig.getExtraInfo()&&!itemConfig.getExtraInfo().equals("")){
                            switch (itemConfig.getExtraInfo()) {
                                case "city":
                                    itemConfig.setTextType(10);
                                    break;
                                case "weather":
                                    itemConfig.setTextType(9);
                                    break;
                            }
                        }

                        break;
                    case 2:
                        //天气图片
                        if (null!=itemConfig.getExtraInfo()&&!itemConfig.getExtraInfo().equals("")){
                            switch (itemConfig.getExtraInfo()) {
                                case "weather":
                                    itemConfig.setElement(9);
                                    itemConfig.setExtraInfo("{\"day\":\"0\"}");
                                    break;
                            }
                        }
                        break;
                }


            });
            item.setWidgeConfigList(widgeConfigList);
        });
        widge.setWidgePreviews(widgePreviews);
        widge.setWidgeSizeList(widgeSizeList);

        //根据组件获取组件的配置列表
//        List<WidgeConfigEntity> widgeConfig = widgeConfigService.queryWidgeConfigList(widgeId);
//
//        widgeConfig.forEach(itemConfig -> {
//            //修改旧数据的文字类型
//            switch (itemConfig.getElement()){
//                case 3:
//                    //电量
//                    itemConfig.setElement(1);
//                    itemConfig.setTextType(8);
//                    break;
//                case 4:
//                    //温度
//                    itemConfig.setElement(1);
//                    itemConfig.setTextType(6);
//                    break;
//                case 8:
//                    //步数
//                    itemConfig.setElement(1);
//                    itemConfig.setTextType(5);
//                    break;
//
//            }
//            //根据组件元素获取天气组图
//            if (itemConfig.getElement() == 9){
//                List<String> weathers =   widgeWeatherImagesService.queryWidgeWeatherImagesByConfigId(itemConfig.getId()+"");
//                if (weathers != null && weathers.size() > 0){
//                    itemConfig.setWeatherImages(weathers);
//                }
//            }
//        });
//        widge.setWidgeConfigList(widgeConfig);
        widge.setWeatherImages( new ArrayList<>());

        //查询详情主题详情图附件
        QueryWrapper<ThemeAttachmentEntity> fileNameWrapper = new QueryWrapper<>();
        fileNameWrapper.and(wrapper -> wrapper
                .eq("type", ThemeAttchmentTypeEnum.WIDGE.getValue())
                .eq("object_id", widge.getId()));
        List<ThemeAttachmentEntity> attachmentList = attachmentService.list(fileNameWrapper);
        if (attachmentList != null && attachmentList.size() > 0) {
            List<String> imageList = new ArrayList<>();
            attachmentList.forEach(attachment -> {
                imageList.add(attachment.getFileUrl());
            });
            widge.setWeatherImages(imageList);
        }
        return R.ok().put("widge", widge);
    }

    @GetMapping("hotBakup")
    @ApiOperation("获取热门组件[前七天下载量最高的]")
    public R hot(@RequestParam(value = "page", defaultValue = "1") String page,
                 @RequestParam(value = "limit", defaultValue = "10") String limit) {
        //1、根据时间查询昨天24小时（一天）
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date startDate = DateHandler.addDateDays(new Date(), -7);
        Date endDate = DateHandler.addDateDays(new Date(), -1);
        Date startTime = DateHandler.getStartTime(startDate);
        Date endTime = DateHandler.getEndTime(endDate);
        Map<String, Object> hotParams = new HashMap<>();
        hotParams.put("type", DownloadTypeEnum.WIDGE.getValue());
        hotParams.put("startTime", formatter.format(startTime));
        hotParams.put("endTime", formatter.format(endTime));
        //2、得的组件id
        List<Long> widgeIds = downloadHistoryService.queryHotDownloadIds(hotParams);
        //3、根据组件id查询
        Map<String, Object> params = new HashMap<>(6);
        Integer status = ThemeStatusEnum.NORMAL.getValue();
        params.put("page", page);
        params.put("limit", limit);
        params.put("ids", widgeIds);
        params.put("themeShow", false);
        params.put("showStatus", 1);
        params.put("status", String.valueOf(status));
        //没有最新下的话数据正常显示几个
        if (widgeIds == null) {
            PageUtils pages = widgeService.queryPageBydistinctName(params);
            List<WidgeEntity> list = (List<WidgeEntity>) pages.getList();
            List<WidgeEntity> newList = new ArrayList<>();
            list.forEach(theme -> {
                //同名组件列表
                List<WidgeEntity> widgeSizeList = widgeService.queryWidgeListByName(theme.getName());
                WidgeEntity widge = widgeSizeList.get(0);
                BeanUtils.copyProperties(widge, theme);
                // 同名组件大小
                WidgePreviews widgePreviews = new WidgePreviews();
                widgeSizeList.forEach(item -> {
                    String widgetSize = item.getWidgetSize();
                    if (widgetSize.equals(WidgeSizeEnum.SMALL.getValue())) {
                        widgePreviews.setSmall(item.getPreview());
                    }
                    if (widgetSize.equals(WidgeSizeEnum.MEDIUM.getValue())) {
                        widgePreviews.setMidium(item.getPreview());
                    }
                    if (widgetSize.equals(WidgeSizeEnum.LAREGE.getValue())) {
                        widgePreviews.setLarge(item.getPreview());
                    }
                    theme.setWidgePreviews(widgePreviews);
                    List<WidgeEntity> newWidgeSizeList = new ArrayList<>();
                    newWidgeSizeList.add(item);
                    theme.setWidgeSizeList(newWidgeSizeList);
                    newList.add(theme);
                });
            });
            pages.setList(newList);
            return R.ok().put("page", pages);
        }

        PageUtils pages = widgeService.queryPageBydistinctNameByIds(params);
        List<WidgeEntity> list = (List<WidgeEntity>) pages.getList();
        List<WidgeEntity> newList = new ArrayList<>();
        list.forEach(theme -> {
            //同名组件列表
            List<WidgeEntity> widgeSizeList = widgeService.queryWidgeListByName(theme.getName());
            WidgeEntity widge = widgeSizeList.get(0);
            BeanUtils.copyProperties(widge, theme);
            // 同名组件大小
            WidgePreviews widgePreviews = new WidgePreviews();
            widgeSizeList.forEach(item -> {
                String widgetSize = item.getWidgetSize();
                if (widgetSize.equals(WidgeSizeEnum.SMALL.getValue())) {
                    widgePreviews.setSmall(item.getPreview());
                }
                if (widgetSize.equals(WidgeSizeEnum.MEDIUM.getValue())) {
                    widgePreviews.setMidium(item.getPreview());
                }
                if (widgetSize.equals(WidgeSizeEnum.LAREGE.getValue())) {
                    widgePreviews.setLarge(item.getPreview());
                }
                theme.setWidgePreviews(widgePreviews);
                List<WidgeEntity> newWidgeSizeList = new ArrayList<>();
                newWidgeSizeList.add(item);
                theme.setWidgeSizeList(newWidgeSizeList);
                newList.add(theme);
            });
        });
        pages.setList(newList);

        return R.ok().put("page", pages);
    }

}
